package com.bird.main;

import com.bird.util.Constant;
import com.bird.util.GameUtil;

import java.awt.*;
import java.awt.image.BufferedImage;

public class Bird {
    //因为小鸟的图片有三张
    public static final int BIRD_IMG_COUNT = 3;
    //鸟的状态
    public static final int STATE_NORMAL = 0;
    public static final int STATE_UP = 1;
    public static final int STATE_DOWN = 2;
    //小鸟是否存活
    public boolean life = true;
    //小鸟矩形判定碰撞对象
    private Rectangle rectangle;
    private int state;
    //小鸟移动方向，上下
    private boolean up = false, down = false;
    //移动速度
    private int speed = 7;
    //加速度
    private int acceleration;

    //鸟的位置
    private int x = 200, y = 200;
    private BufferedImage[] images;

    public Bird() {
        images = new BufferedImage[BIRD_IMG_COUNT];
        for (int i = 0; i < BIRD_IMG_COUNT; i++) {
            images[i] = GameUtil.loadBufferedImage(Constant.BIRD_IMG_PATH[i]);
        }
        this.rectangle = new Rectangle(images[0].getWidth(), images[0].getHeight());
    }

    public Rectangle getRectangle() {
        return rectangle;
    }

    public void draw(Graphics g) {
        //需要在这比使用控制鸟飞行方向的方法
        flyLogic();
        g.drawImage(images[state], x, y, null);
        //TODO:小鸟的矩形依旧存在,只是不再绘制出来
        //g.drawRect(x, y, rectangle.width, rectangle.height);
        rectangle.x = this.x;
        rectangle.y = this.y;
    }

    //    控制鸟的移动方向
    public void flyLogic() {
        if (up) {
            acceleration--;
            //y是相对与左上角而言，并不是越大越上而是越大越下
            y += acceleration;
            if (acceleration < -10) {
                acceleration = -10;
            }
            //不超出窗口
            if (y < 20)
                y = 20;
        } else {
            acceleration++;
            y += acceleration;
            if (acceleration > 5) {
                acceleration = 5;
            }
            //模拟自由落体
            y += speed;
            //不落到地面
            if (y > 450) {
                y = 450;
                acceleration = 0;
            }
        }
    }

    //鸟的飞行，按抬各是一次，图片改变两次
    public void fly(int fly) {
        switch (fly) {
            case 1:
                state = 1;
                up = true;
                break;
            case 5:
                state = 2;
                up = false;
                break;
        }
    }

    public void reStart(GameFrame gameFrame) {
        life = true;
        x = 200;
        y = 200;
        gameFrame.restartMusic();
    }
}
